<template>
  <div class="EditPersonalInformation">
    <NavBar title="编辑个人资料" placeholder :zIndex="10000">
      <template #left>
        <div class="left" @click="handleClick">
          <Icon name="zuojiantou" size="18" color="#fff"></Icon>
        </div>
      </template>
    </NavBar>
    <!-- 上传头像区域 -->
    <div class="upload_avatar">
      <div class="avatar">
        <img class="avatar_img" :src="backupUserInfo.userAvatar" alt="头像">
        <input type="file" class="avatar_input" ref="fileInput" accept="image/*" @change="handleAvatarChange">
      </div>
      <div class="upload_text">点击更换头像</div>
    </div>
    <div class="from">
      <div class="from_item">
        <div class="from_item_label">昵称:</div>
        <div class="from_item_input">
          <input type="text" placeholder="请输入昵称" v-model="backupUserInfo.userNickname">
        </div>
      </div>
      <div class="from_item">
        <div class="from_item_label">签名:</div>
        <div class="from_item_input">
          <input type="text" placeholder="请输入签名" v-model="backupUserInfo.userDesc">
        </div>
      </div>
      <div class="from_item">
        <div class="from_item_label">性别</div>
        <div class="from_item_input">
          <div class="from_item_input_item" :class="[
            { active: backupUserInfo.userGender === '男' },
            { male: backupUserInfo.userGender === '男' },
            { female: backupUserInfo.userGender === '女' }
          ]" @click="backupUserInfo.userGender = '男'">
            <Icon name="nanxing" size="16" color="#1E3A8A"></Icon>
            <div class="from_item_input_item_text">男性</div>
          </div>

          <div class="from_item_input_item" :class="[
            { active: backupUserInfo.userGender === '女' },
            { female: backupUserInfo.userGender === '女' },
            { male: backupUserInfo.userGender === '男' }
          ]" @click="backupUserInfo.userGender = '女'">
            <Icon name="women-line" size="16" color="#F986C1"></Icon>
            <div class="from_item_input_item_text">女性</div>
          </div>
        </div>
      </div>
      <div class="from_item">
        <div class="from_item_label">年龄</div>
        <div class="from_item_input">
          <input type="number" placeholder="请输入年龄" v-model="backupUserInfo.userAge">
        </div>
      </div>
      <div class="from_item">
        <div class="from_item_label">地区</div>
        <div class="from_item_input">
          <input type="text" placeholder="请输入地区" v-model="backupUserInfo.userAddress">
        </div>
      </div>
    </div>
    <Teleport to="body">
      <ImageCropper v-model="cropperVisible" :image-src="cropperImageSrc" @confirm="handleCropConfirm"
        v-show="cropperVisible" />
    </Teleport>
  </div>

</template>

<script setup>
import { ref, computed, defineAsyncComponent, reactive } from 'vue'
import { editUserInfoAPI } from '@/api/my'

import { showDialog } from '@/utils/showDialog'
import { Toast } from '@/utils/showtoast'

import Icon from '@/components/common/Icon.vue'
import NavBar from '@/components/common/Navbar.vue'
const ImageCropper = defineAsyncComponent(() => import('@/views/my/ImageCropper.vue'))


// 1.用户信息 - 本地存储
import { useUserStore } from '@/stores/userinfo'
const userInfo = useUserStore()
const user = computed(() => userInfo.userInfo)
const { userId } = user.value || {}

// 备份用户信息
let backupUserInfo = reactive({ ...user.value })

const model = defineModel()
function isObjectEqual(a, b) {
  const aKeys = Object.keys(a)
  const bKeys = Object.keys(b)
  if (aKeys.length !== bKeys.length) return false
  for (let key of aKeys) {
    // 跳过头像字段的比较，因为头像已经单独处理
    if (key === 'userAvatar') continue
    if (a[key] !== b[key]) return false
  }
  return true
}
const handleClick = () => {
  // 返回的时候判断是否有修改
  if (!isObjectEqual(backupUserInfo, user.value)) {
    showDialog({
      title: '提示',
      message: '是否保存修改',
      onConfirm: () => {
        handleEdit()
      },
      onCancel: () => {
        console.log('已取消')
        model.value = false
      }
    })
  } else {
    model.value = false
  }
}
// 编辑函数
const handleEdit = async () => {
  // 调用编辑用户信息接口
  const res = await editUserInfoAPI(userId, {
    userAddress: backupUserInfo.userAddress,
    userAge: backupUserInfo.userAge,
    userDesc: backupUserInfo.userDesc,
    userGender: backupUserInfo.userGender,
    userNickname: backupUserInfo.userNickname,
  })
  console.log(res)
  if (res.code === 200) {
    userInfo.setUserInfo({
      ...res.data,
      userAvatar: backupUserInfo.userAvatar, // 保持当前头像
    })
    Toast('修改成功', {
      position: 'bottom',
    })
    model.value = false
  }
}


// // 上传头像事件
const cropperVisible = ref(false)
const cropperImageSrc = ref('')

const handleAvatarChange = (e) => {
  const file = e.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      // 显示裁剪器
      cropperVisible.value = true
      cropperImageSrc.value = reader.result
    }
  }
  // 清空input的value，确保下次选择相同文件也能触发chan      ge事件
  e.target.value = ''
}

const handleCropConfirm = (croppedImageUrl) => {
  // 显示对话框询问是否保存头像
  showDialog({
    title: '提示',
    message: '是否保存新头像？',
    onConfirm: () => {
      // 保存头像到用户信息
      userInfo.setUserInfo({
        ...user.value,
        userAvatar: croppedImageUrl,
      })
      // 同时更新备份信息
      backupUserInfo.userAvatar = croppedImageUrl
      Toast('头像保存成功', {
        position: 'bottom',
      })
    },
    onCancel: () => {
      // 不保存，什么都不做
      console.log('取消保存头像')
    }
  })
}
</script>

<style lang="scss" scoped>
.EditPersonalInformation {
  @include fixed-top;
  background-color: #211832;
  height: 100vh;

  .upload_avatar {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
    border-bottom: 1px solid #292825cc;
    -webkit-tap-highlight-color: transparent;


    .avatar {
      position: relative;
      width: 100px;
      height: 100px;
      border-radius: 50%;
      overflow: hidden;
      cursor: pointer;

      .avatar_img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .avatar_input {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        cursor: pointer;
      }
    }

    .upload_text {
      margin-top: 10px;
      font-size: 12px;
      color: #879394;
      cursor: pointer;
      font-weight: bold;
    }
  }

  .from {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    gap: 30px;
    padding: 20px;
    border-radius: 10px;

    .from_item {
      display: flex;
      align-items: center;
      gap: 5px;

      .from_item_label {
        font-size: 14px;
        color: #fff;
        flex-shrink: 0;
        width: 60px;
      }

      .from_item_input {
        flex: 1;
        display: flex;
        gap: 16px;
        align-items: center;

        input {
          width: 100%;
          padding: 10px;
          color: #fff;
          background-color: transparent;
          border-bottom: 1px solid #292825cc;
        }

        .from_item_input_item {
          -webkit-tap-highlight-color: transparent;
          -webkit-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
          outline: none;
          touch-action: manipulation;

          width: 45px;
          height: 45px;
          padding: 8px;
          border-radius: 50%;
          color: #fff;
          background-color: #2a1d3c;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          cursor: pointer;
          transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);

          &:hover {
            transform: scale(1.05);
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.1);
          }

          .from_item_input_item_text {
            font-size: 10px;
            font-weight: bold;
            line-height: 1;
            color: #ccc;
            margin-top: 2px;
            transition: color 0.3s ease;
          }

          &.active {
            transform: scale(1.1);
            color: #fff;

            .from_item_input_item_text {
              color: #000;
            }

            &.male {
              background-color: #209ff5;
              animation: pulsingShadowBlue 2s infinite ease-out;
            }

            &.female {
              background-color: #ee4fb2;
              animation: pulsingShadowPink 2s infinite ease-out;
            }
          }
        }
      }
    }
  }
}

// 蓝色脉动阴影（男性）
@keyframes pulsingShadowBlue {
  0% {
    box-shadow:
      0 0 0 2px rgba(255, 255, 255, 0.2),
      0 4px 12px rgba(32, 159, 245, 0.5),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }

  50% {
    box-shadow:
      0 0 0 8px rgba(255, 255, 255, 0),
      0 8px 24px rgba(32, 159, 245, 0.6),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }

  100% {
    box-shadow:
      0 0 0 12px rgba(255, 255, 255, 0),
      0 12px 32px rgba(32, 159, 245, 0.4),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }
}

// 粉色脉动阴影（女性）
@keyframes pulsingShadowPink {
  0% {
    box-shadow:
      0 0 0 2px rgba(255, 255, 255, 0.2),
      0 4px 12px rgba(238, 79, 178, 0.5),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }

  50% {
    box-shadow:
      0 0 0 8px rgba(255, 255, 255, 0),
      0 8px 24px rgba(238, 79, 178, 0.6),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }

  100% {
    box-shadow:
      0 0 0 12px rgba(255, 255, 255, 0),
      0 12px 32px rgba(238, 79, 178, 0.4),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }
}
</style>